package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.BeanUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.bean.SystemParam;
import com.mock.ems.common.JsonResult;

import java.util.*;

/**
 * Created by lichengming on 2017/6/14.
 */
public class SystemParamController extends Controller {

    public void index() {
        renderJsp("/page/systemparam/system_param_list.jsp");
    }

    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        StringBuilder exceptSelectSQL = new StringBuilder(" from system_param where 1 = 1 ");
        List<Object> params = new ArrayList<Object>();

        String name = getPara("name");
        if (StringUtil.isNotEmpty(name)) {
            exceptSelectSQL.append(" and name like ?");
            params.add("%" + name.trim() + "%");
        }

        String key = getPara("pkey");
        if (StringUtil.isNotEmpty(key)) {
            exceptSelectSQL.append(" and pkey like ? ");
            params.add("%" + key.trim() + "%");
        }


        exceptSelectSQL.append(" order by update_time desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, "select id,pkey,pvalue,status,name,create_time,to_client ", exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, "select id,pkey,pvalue,status,name,create_time,to_client ", exceptSelectSQL.toString(),params.toArray());
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void edit() {
        Record record = Db.findById("system_param", getPara("systemParamId"));
        if (null != record) {
            setAttr("systemParam", record.getColumns());
        }
        renderJsp("/page/systemparam/system_param_add.jsp");
    }

    @Before(Tx.class)
    public void save() {

        SystemParam systemParam = getBean(SystemParam.class,"");
        JsonResult result = new JsonResult();
        Record record = new Record();
        try {
            record.setColumns(BeanUtil.objectToMap(systemParam));
        } catch (Exception e) {
            renderJson(result.status("-1").show("保存失败"));
            return;
        }

        boolean success;
        if (systemParam.getId() == null) {
            if (isSystemParamExist(systemParam.getPkey())) {
                renderJson(result.status("-2").show("参数已存在，请重新填写"));
                return;
            }
            success = Db.save("system_param",record);
        }else {
            record.set("update_time",new Date());
            success = Db.update("system_param",record);
        }

        if (success) {
            renderJson(result.status("000").show("保存成功"));
        }else {
            renderJson(result.status("-3").show("保存失败"));
        }
    }

    public void delete() {

        String systemParamIdList = getPara("systemParamIdList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(systemParamIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from system_param where id in (");
        Object [] systemParams = new Object[systemParamIdList.split(",").length];
        int index = 0;
        for (String id : systemParamIdList.split(",")) {
            deleteSQL.append("?,");
            systemParams[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");


        boolean deleteResult = Db.update(deleteSQL.toString(),systemParams) == systemParams.length;
        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

    private boolean isSystemParamExist(String pkey) {
        String sql = "select id from system_param where pkey = ? ";
        return Db.findFirst(sql,pkey) != null;
    }

    public void isSystemParamExist() {
        String sql = "select id from system_param where pkey = ? ";
        String loginAccount = getPara("key");
        Record record = Db.findFirst(sql,loginAccount);
        renderJson(record == null ? true:false);
    }

}
